import { Veh, VehCost } from "../models/veh";
import { TransOrder } from "../models/order";
import dayjs from "dayjs";
import { VehCostType } from "../utils/const";
export default function vehmodule(app, opt, next) {
  app.get("list", (req, res) => {
    return res.createPagination(Veh);
  });
  app.post("add", async (req, res) => {
    const model = new Veh(req.body);
    model.status = 1;
    await model.save();
    return model;
  });
  app.post("update", async (req, res) => {
    const { id, ...rest } = req.body;
    await Veh.updateOne({ _id: id }, { $set: rest });
    return { msg: "ok" };
  });
  app.post("delete", async (req, res) => {
    const { id } = req.body;
    await Veh.deleteOne({ _id: id });
    return { msg: "ok" };
  });
  app.get("details", async (req, res) => {
    const { id, begin, end } = req.query;

    const veh = await Veh.findById(id);
    if (!veh) {
      throw new Error("车辆不存在");
    }

    const transOrders = await TransOrder.find({
      veh_plate: veh.plate,
      begin_at: {
        $gte: dayjs(begin).toDate(),
        $lte: dayjs(end).toDate(),
      },
    });
    const costs = await VehCost.find({
      plate: veh.plate,
      date: {
        $gte: dayjs(begin).toDate(),
        $lte: dayjs(end).toDate(),
      },
    });

    return {
      orders: transOrders.reduce((acc, cur) => {
        const k = dayjs(cur.begin_at).format("YYYY-MM-DD");
        if (!acc[k]) {
          acc[k] = [];
        }
        acc[k].push(cur);
        return acc;
      }, {}),
      costs,
      veh,
    };
  });

  app.post("save-cost", async (req) => {
    const { body } = req;
    const date = new Date(body.date);
    let model = await VehCost.findOne({
      plate: body.plate,
      key: body.key,
      date,
    });
    if (!model) {
      model = new VehCost();
      model.date = date;
      model.key = body.key;
      model.plate = body.plate;
    }

    model.value = body.value;
    await model.save();
    return model;
  });
  next();
}
export const autoPrefix = "/veh/";
